from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from datetime import datetime
import time as atime

from ..database import get_db
from ..crud import weather as crud_weather
from ..schemas import weather as schemas_weather

router = APIRouter(
    prefix="/api/v1/weather",
    tags=["Weather"],
)

@router.get("", response_model=schemas_weather.WeatherResponse)
def get_weather(time: datetime, db: Session = Depends(get_db)):
    """
    获取指定时间点的天气信息。
    接口会返回在指定时刻之前或恰好在该时刻的、最接近的一条天气记录。
    """
    print(f"Received request for weather at time: {time.isoformat()}")
    start_time = atime.time()

    weather_record = crud_weather.get_weather_by_time(db, time)
    
    if not weather_record:
        # 如果找不到任何记录（例如请求时间早于所有数据），返回 404
        raise HTTPException(status_code=404, detail="在指定时间之前未找到天气数据")
        
    # 使用 Pydantic 模型自动完成数据映射和格式化
    weather_info = schemas_weather.WeatherInfo.from_orm(weather_record)
    
    response_data = {
        "requested_time": time,
        "record_time": weather_record.dt,
        "weather": weather_info
    }
    end_time = atime.time()
    print(f"Processed weather request in {end_time - start_time:.3f} seconds")
    return {
        "code": 0,
        "message": "success",
        "data": response_data
    }